#!/usr/bin/env python
# encoding: utf-8
# @author: qiaowei
# @license: (C) Copyright 2013-2019
# @contact: weiweiqiao@126.com
# @file: file_manager_module.py
# @time: 2020/6/19
# @desc:

# import decimal
import copy

from fractions import Fraction
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QFileDialog
from PySide2.QtCore import QFileInfo
from PySide2.QtCore import Signal
from PySide2.QtCore import Slot

from py_package.information_module import Information
from py_package.table_model_module import TableModel
from py_package.data_processing import DataProecesing


class FileManager:
    def __init__(self):
        self.__table_model = TableModel()
        self.__data_processing = DataProecesing()
        self.__signal_read_file = Signal(str)
        # pass

    def exit_application(self):
        """
        退出窗体

        """
        QApplication.closeAllWindows()

    def read_file(self):
        """
        打开对话框，选择要显示的台站txt文件
        :return: 元组，包含2部分内容，打开的txt文件名称（具体台站）；包含台站频率信息的模型model。当
            内容不存在或不符合要求时，在元组相应位置填充None替代
        """
        file_name_and_path_in_tuple = QFileDialog.getOpenFileName()
        if file_name_and_path_in_tuple == ('', ''):
            return None, None

        # 获取打开文件的名称（包括后缀名）
        file_name_and_path = file_name_and_path_in_tuple[0]
        # label.setText(file_name_and_path_in_tuple[0].replace('.txt', '').split('/')[-1])
        information_list = []

        # 以只读方式打开文件，允许缓冲，编码格式为utf-8
        with open(file_name_and_path, 'r', buffering=True, encoding='utf-8') as file:
            # 读取文件信息并保存
            for line in file.readlines():
                line = line.replace('\n', '')
                line = line.split('-')
                temp = Information(line[0], float(line[1]))
                information_list.append(temp)

        # 将文件名所有字符小写。用''替换'.txt'并返回
        # text = file_name_and_path_in_tuple[0].lower().replace('.txt', '').split('/')[-1]
        text = QFileInfo(file_name_and_path).fileName().lower().replace('.txt', '')

        if 0 != len(information_list):
            # 从文件中读取到频率数据
            return text, self.set_model(information_list)
        else:
            return text, None

    def read_file_in_multithread(self):
        file_name_and_path_in_tuple = QFileDialog.getOpenFileName()
        if ('', '') == file_name_and_path_in_tuple:
            return None, None

    def set_model(self, informations: list):
        # if self.__table_model == None:
        #     self.__table_model = TableModel()

        self.__table_model.set_model(informations)

        return self.__table_model

    def calculate_frequency(self, value: float):
        information_list = self.__table_model.informations
        count = len(information_list)
        for index in range(0, count):
            if information_list[index].inter_modulation:
                information_list[index].inter_modulation = False
                information_list[index].inter_modulation_frequency = 0

        information_list = self.__test_frequency(count, value, information_list)

        # 更新模型
        self.__table_model.beginResetModel()
        self.__table_model.set_model(information_list)
        self.__table_model.endResetModel()

    def __test_frequency(self, count: int, value: float, information_list: list):
        """
        根据公式计算传入频率与台站频率是否有互调干扰，更新保存台站频率的list的是否互调、互调频率信息
        :param count: 台站的频率个数
        :param value: 传入的频率
        :param information_list: 保存台站频率信息的list
        :return: 返回更新后的台站频率list
        """
        for index in range(0, count):
            cal = value * 2 - information_list[index].frequency
            for i in range(0, count):
                if 0.0001 > abs(cal - information_list[i].frequency):
                    information_list[index].inter_modulation = True
                    information_list[index].inter_modulation_frequency = cal

        for index in range(0, count):
            cal = information_list[index].frequency * 2 - value
            for i in range(0, count):
                if 0.0001 > abs(information_list[i].frequency - cal):
                    information_list[index].inter_modulation = True
                    information_list[index].inter_modulation_frequency = cal

        return information_list

    # def __init_connection_and_thread(self):
        # self.__signal_read_file.emit
